package org.zachary.creditbusiness.commodityandhouse.scheduler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.stereotype.Component;
import org.zachary.creditbusiness.hotel.entity.Ban;
import org.zachary.creditbusiness.hotel.mapper.BanMapper;
import org.zachary.creditbusiness.commodityandhouse.entity.HouseOrder;
import org.zachary.creditbusiness.commodityandhouse.mapper.HouseOrderMapper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
@Slf4j
public class HouseBanScheduler {

    private final HouseOrderMapper houseOrderMapper;
    private final BanMapper banMapper;

    private static final DateTimeFormatter DTF =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    public HouseBanScheduler(HouseOrderMapper houseOrderMapper, BanMapper banMapper) {
        this.houseOrderMapper = houseOrderMapper;
        this.banMapper = banMapper;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        log.info("ApplicationReadyEvent — house extreme-overdue ban check");
        checkAndBan();
    }

    /**
     * 检查房屋租赁订单中超过180天的逾期订单并进行封禁
     */
    private void checkAndBan() {
        LocalDate today = LocalDate.now();
        log.info("Checking house extreme overdue at {}", today);

        // 查询所有已逾期(promise=2)且未支付(status=0)的房屋订单
        QueryWrapper<HouseOrder> qw = new QueryWrapper<>();
        qw.eq("promise", 2)
                .eq("status", 0);
        List<HouseOrder> list = houseOrderMapper.selectList(qw);
        log.info("Found {} overdue unpaid house orders", list.size());

        for (HouseOrder order : list) {
            try {
                if (order.getDeadline() == null) {
                    log.warn("House order {} has null deadline, skipping", order.getId());
                    continue;
                }

                LocalDate deadline = order.getDeadline().toLocalDateTime().toLocalDate();
                long days = ChronoUnit.DAYS.between(deadline, today);

                if (days <= 180) {
                    continue; // 未超过180天，跳过
                }

                String banUuid = order.getUuid();
                if (banUuid == null || banUuid.trim().isEmpty()) {
                    log.warn("House order {} has null/empty UUID, skipping ban", order.getId());
                    continue;
                }

                // 检查是否已经被封禁
                QueryWrapper<Ban> banQuery = new QueryWrapper<>();
                banQuery.eq("uuid", banUuid);
                long existingBanCount = banMapper.selectCount(banQuery);

                if (existingBanCount > 0) {
                    log.debug("User {} already banned for house order {}, skipping",
                            order.getUserId(), order.getId());
                    continue;
                }

                // 创建封禁记录
                Ban ban = new Ban();
                ban.setUuid(banUuid);
                ban.setUserId(order.getUserId().longValue());
                ban.setBan(1); // 1表示封禁

                int inserted = banMapper.insert(ban);
                if (inserted > 0) {
                    log.info("Banned user {} for house order {} (UUID: {}, overdue {} days)",
                            order.getUserId(), order.getId(), banUuid, days);
                } else {
                    log.error("Failed to insert ban record for user {} house order {}",
                            order.getUserId(), order.getId());
                }

            } catch (Exception e) {
                log.error("Error processing house order {} for ban check: {}",
                        order.getId(), e.getMessage(), e);
            }
        }
    }
}